# -*- coding: utf-8 -*-
import json
import os
import time

from odoo import http


# from weixin import weixin_controllers
from odoo.addons.weixin.api.weixinapi import WeiXinApi
from odoo.addons.weixin.api.session_manager import session_obj
from odoo.addons.weixin.api.weixinapi import WeiXinApiObj

import logging

_loggle = logging.getLogger(__name__)


class WliotMineController(http.Controller):

    @http.route('/wliot/mine/queryUserInfo', auth='public')
    def queryUserInfo(self, **kw):
        ''' 查询用户信息 '''
        try:
            partner = self.get_partner_by_session_id(kw)

            data = {
                'name': partner.name,
                'phone': partner.phone,
                'headIcon': partner.head_icon,
                'password': partner.password,
                'bindStatus': partner.bind_status,
                'setting_permission': partner.setting_permission,
                'control_permission': partner.control_permission
            }
            return json.dumps({
                'success': True,
                'message': u'查询成功！',
                'data': data
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': error
                })

    @http.route('/wliot/mine/changeHeadIcon', auth='none', csrf=False)
    def changeHeadIcon(self, **kw):
        ''' 更换头像 '''
        # try:
        partner = self.get_partner_by_session_id(kw)
        if not partner:
            return json.dumps({
                'success': False,
                'code': 500,
                'message': self.get_partner_by_session_id(kw)
            })

        _loggle.info(json.loads(kw))

        upload_file = http.request.files['file']
        # upload_file = http.request.files.getlist()
        _loggle.info(upload_file)

        old_file_name = upload_file.filename
        if upload_file:
            file_path = os.path.join('/home/local/upload/', old_file_name)
            upload_file.save(file_path)
            _loggle.info('file saved to %s' % file_path)
        # url = http.request.env['image'].upload_image_to_oss(data)
        partner.write({
            'head_icon': file_path,
        })
        return json.dumps({
            'data': {'url': file_path},
            'success': True,
            'msg': '',
        })
        # except Exception, e:
        #     try:
        #         error = e[0]
        #     except:
        #         error = str(e)
        #     finally:
        #         return json.dumps({
        #             'success': False,
        #             'code': 500,
        #             'message': error
        #         })

    @http.route('/wliot/mine/changeName', auth='public', csrf=False)
    def changeName(self, **kw):
        ''' 更换姓名 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            new_name = kw.get('newName')
            partner.sudo().write({'name': new_name})
            return json.dumps({
                'success': True,
                'message': u'更换成功！',
                'code': 200
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': error
                })

    @http.route('/wliot/mine/changePassword', auth='public', csrf=False)
    def changePassword(self, **kw):
        ''' 更换密码 '''
        try:
            new_password = kw.get('newPassword')

            session_id = kw.get('SessionID')
            if not session_id:
                return json.dumps({
                    'success': False,
                    'msg': u'请传入SessionID！',
                    'code': 400,
                })
            v_code = kw.get('vCode')
            if not v_code:
                return json.dumps({
                    'success': False,
                    'msg': u'请填写验证码！',
                    'code': 400,
                })
            open_id = session_obj.pydis.get(session_id)
            if not open_id:
                return json.dumps({
                    'success': False,
                    'code': 900,
                    'msg': 'session过期！',
                })
            partner = self.get_partner_by_session_id(kw)
            # 验证电话
            check_result = self.check_phone_legal(partner.phone)
            if not check_result['success']:
                return json.dumps({
                    'success': False,
                    'message': check_result['msg'],
                    'code': 500
                })
            check_resul = http.request.env['phone.verify.wizard'].sudo().check_mobile_verify_code(partner.phone,
                                                                                                  v_code)  # 校验验证码
            if check_resul['success']:
                partner.sudo().write({'password': new_password})
                return json.dumps({
                    'success': True,
                    'message': u'更换成功！',
                    'code': 200
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': error
                })

    @http.route('/wliot/mine/userUnbind', auth='public', csrf=False)
    def userUnbind(self, **kw):
        ''' 解除绑定 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            partner.sudo().write({'bind_status': False})
            session_id = kw.get('SessionID')
            if not session_id:
                return json.dumps({
                    'success': False,
                    'msg': u'请传入SessionID！',
                    'code': 400,
                })
            open_id = session_obj.pydis.get(session_id)
            if not open_id:
                return json.dumps({
                    'success': False,
                    'code': 900,
                    'msg': 'session过期！',
                })
            us = http.request.env['weixin.user'].sudo().search([
                ('open_id', '=', open_id)
            ])

            us.sudo().unlink()

            return json.dumps({
                'success': True,
                'message': u'成功解除！',
                'code': 200
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': error
                })

    @http.route('/wliot/mine/queryOperateLogs', auth='public', csrf=False)
    def queryOperateLogs(self, **kw):
        '''' 查询操作日志 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            type = kw.get('type')  # setting 设置   control 控制
            command_logs = http.request.env['wliot.device.command.log'].sudo().search([
                ('partner_id', '=', partner.id),
                ('order_type', '=', type)
            ])
            data = []
            for command_log in command_logs:
                data.append(command_log.get_value())
            return json.dumps({
                'success': True,
                'message': u'请求成功！',
                'data': data
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/queryChildAccount', auth='public')
    def queryChildAccount(self, **kw):
        ''' 查询子账号 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            child_accounts = http.request.env['res.partner'].sudo().search([
                ('parent_id', '=', partner.id)
            ])
            data = []
            for child_account in child_accounts:
                data.append(child_account.get_message())
            return json.dumps({
                'success': True,
                'message': u'请求成功！',
                'data': data
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/addChildAccount', auth='public', csrf=False)
    def addChildAccount(self, **kw):
        ''' 添加子账号 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            account = kw.get('account')
            password = kw.get('password')
            setting_permission = True if kw.get('settingPermission') == 'true' else False
            control_permission = True if kw.get('controlPermission') == 'true' else False
            note = kw.get('note')

            rp = http.request.env['res.partner']
            pp = rp.sudo().search([
                ('name', '=', account)
            ])
            if pp:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': u'该子账号已存在！'
                })
            rp.sudo().create({
                'name': account,
                'password': password,
                'setting_permission': bool(setting_permission),
                'control_permission': bool(control_permission),
                'mobile': account,
                'phone': account,
                'note': note,
                'parent_id': partner.id,
            })

            return json.dumps({
                'code': 200,
                'success': True,
                'message': u'添加成功！'
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/deleteChildAccount', auth='public', csrf=False)
    def deleteChildAccount(self, **kw):
        ''' 删除子账号 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            account = kw.get('account')

            child = http.request.env['res.partner'].sudo().search([
                ('name', '=', account),
                ('parent_id', '=', partner.id)
            ])
            if not child:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': u'该子账号不存在！'
                })
            else:
                child.unlink([
                    ('name', '=', account),
                    ('parent_id', '=', partner.id)
                ])
                return json.dumps({
                    'code': 200,
                    'success': True,
                    'message': u'删除成功！'
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/updateChildAccount', auth='public', csrf=False)
    def updateChildAccount(self, **kw):
        ''' 修改子账号 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            account = kw.get('account')
            password = kw.get('password')
            setting_permission = True if kw.get('settingPermission') == 'true' else False
            control_permission = True if kw.get('control_permission') == 'true' else False
            note = kw.get('note')

            child = http.request.env['res.partner'].sudo().search([
                ('name', '=', account),
                ('parent_id', '=', partner.id)
            ])
            if not child:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': u'该子账号不存在！'
                })
            else:
                child.write({
                    'password': password,
                    'setting_permission': bool(setting_permission),
                    'control_permission': bool(control_permission),
                    'note': note,
                    'parent_id': partner.id,
                })
                return json.dumps({
                    'code': 200,
                    'success': True,
                    'message': u'修改成功！'
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/companyIns', auth='public')
    def companyIns(self, **kw):
        ''' 查询公司简介 '''
        try:
            return json.dumps({
                'success': True,
                'message': u'查询成功！',
                'data': {
                    'introduction': u'万龙简介'
                }
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/queryManual', auth='public')
    def queryManual(self):
        ''' 查询使用手册 '''
        try:
            return json.dumps({
                'success': True,
                'message': u'查询成功！',
                'data': u'这是使用说明'
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/queryLegalMandate', auth='public')
    def queryLegalMandate(self):
        ''' 查询法律授权 '''
        try:
            return json.dumps({
                'success': True,
                'message': u'查询成功！',
                'data': u'这是法律授权'
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/problemFeedback', auth='public', csrf=False)
    def problemFeedback(self, **kw):
        ''' 问题反馈 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            description = kw.get('description')

            http.request.env['wliot.problem.feedback'].sudo().create({
                'partner_id': partner.id,
                'problem': description,
            })
            return json.dumps({
                'code': 200,
                'success': True,
                'message': u'提交成功！'
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/mine/contactUs', auth='public')
    def contactUs(self):
        ''' 联系我们 '''
        try:
            data = {
                'address': http.request.env['ir.config_parameter'].get_param('our_address'),
                'tel': http.request.env['ir.config_parameter'].get_param('our_tel'),
                'fax': http.request.env['ir.config_parameter'].get_param('our_fax'),
                'email': http.request.env['ir.config_parameter'].get_param('our_email')
            }
            return json.dumps({
                'success': True,
                'message': u'查询成功！',
                'data': data
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    def get_partner_by_session_id(self, kw):
        '''检查session是否过期，并根据session_id返回该微信号可以查看的客户'''
        session_id = kw.get('SessionID')
        if not session_id:
            return {
                'success': False,
                'code': 400,
                'msg': u'请传入session_id！',
            }
        open_id = session_obj.pydis.get(session_id)
        if not open_id:
            return {
                'success': False,
                'code': 900,
                'msg': u'sessoin已过期，请重新获取！',
            }
        wechat_recs = http.request.env['weixin.user'].sudo().search([('open_id', '=', open_id)])
        partner = http.request.env['res.partner'].sudo().search([('id', '=', wechat_recs.partner_id.id)])
        return partner

    def check_phone_legal(self, phone):
        '''是否存在该电话的客户，若存在则返回该客户'''
        records = http.request.env['res.partner'].sudo().search([
            # ('partner_type', '=', 'customer'),
            ('phone', '=', phone)
        ])
        if not records:
            return {
                'success': False,
                'msg': u'不存在电话为%s的客户！' % phone,
            }
        else:
            return {
                'success': True,
                'value': records,
            }